package com.bonc.modules.rpt.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonc.common.utils.Result;
import com.bonc.modules.rpt.entity.SunshineActionEntity;
import com.bonc.modules.rpt.listener.SunshineActionListener;
import com.bonc.modules.rpt.param.SunshineActionParam;
import com.bonc.modules.rpt.service.SunshineActionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author jinlong
 * @date 2021/8/4
 */
@Controller
@RequestMapping("/rpt/sunshine-action")
public class SunshineActionController {


    @Autowired
    private SunshineActionService sunshineActionService;


    @GetMapping("/page")
    @ResponseBody
    public Result page(SunshineActionParam sunshineActionParam) {
        Page<SunshineActionEntity> page = sunshineActionService.page(sunshineActionParam);
        return Result.ok().put("page", page);
    }


    @GetMapping("/totalList")
    @ResponseBody
    public Result totalList(SunshineActionParam sunshineActionParam) {
        List<Map> list = sunshineActionService.totalList(sunshineActionParam);
        return Result.ok().put("list", list);
    }


    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody @Validated(SunshineActionParam.delete.class) SunshineActionParam sunshineActionParam) {
        int deleteCount = sunshineActionService.delete(sunshineActionParam);
        if (deleteCount > 0) {
            return Result.ok();
        }
        return Result.error("删除失败");

    }


    /**
     * 上传数据文件
     *
     * @param file 数据文件
     * @return 上传结果
     * @throws IOException 文件读取IO异常
     */
    @PostMapping("upload")
    @ResponseBody
    @RequiresPermissions("sudden-event:upload")
    public Result upload(@RequestPart("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), SunshineActionEntity.class, new SunshineActionListener(sunshineActionService)).sheet().doRead();
        return Result.ok();
    }

    @GetMapping("downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            // 通过url获取File的绝对路径
            InputStream is = this.getClass().getResourceAsStream(File.separator + "static" + File.separator + "template" + File.separator + "阳光行动报表模板.xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("阳光行动报表模板.xlsx", "UTF-8"));

            //从内存中写出来
            if (is != null) {
                IoUtil.copy(is, os);
                os.flush();
                IoUtil.close(os);
                IoUtil.close(is);
            } else {
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println(JSONUtil.toJsonStr(Result.error("下载文件失败,请联系管理员")));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("/excel")
    public void downloadFailedUsingJson(HttpServletResponse response, SunshineActionParam sunshineActionParam) throws IOException {
        List<SunshineActionEntity> data = sunshineActionService.list(sunshineActionParam);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("阳光行动明细", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), SunshineActionEntity.class).autoCloseStream(Boolean.TRUE).sheet("sheet1")
                    .doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONUtil.toJsonStr(Result.error("下载文件失败,请联系管理员")));
        }
    }

}
